var mysql = require('mysql')

var pool = mysql.createPool({
    connectionLimit: 100,
    connectTimeout: 60000,
    acquireTimeout: 60000,
    timeout: 60000,
    host: '8.136.153.141',
    port: '3306',
    user: 'pms',
    password: 'pms',
    database: 'dispatch_order',
    timezone: '08:00',   //"08:00"  'utc' 'SYSTEM'
    multipleStatements: true,   //允许多条语句
    allowMultiQueries:true
})

this.query = function(sqlStr) {
    if (!sqlStr) {
        // 同步中throw错误，相当于返回reject状态的Promise
        throw new Error('Invalid sqlStr.')
    }
    return new Promise((resolve, reject) => {
        try {
            // 异步中throw错误，会造成无法捕捉，需要在外层加一个catch
            pool.getConnection(function(connectErr, connection) {
                if (connectErr) {
                    reject(connectErr)
                    return
                }
                connection.query(sqlStr, function(err, results, fields) {
                    // 归还到连接池
                    // connection.release()
                    // 从连接池中移除
                    connection.destroy()
                    if (err) {
                        reject(err)
                        return
                    }
                    resolve(results)
                })
            })
        } catch (err) {
            reject(err)
        }
    })
}

module.exports = this
